import React, { memo, useState, useEffect } from "react";
import { AskChildMomentDetailCommentWrapper } from "./style";
import { MOMENT_DETAIL_COMMENT_PAGESIZE } from "@/common/contants";
import { Input, Button, message, Empty } from "antd";
import { isToken } from "@/hooks";
import { useHistory } from "react-router-dom";
import { handleComment, deDuplication } from "@/utils/comment";
import CommentDetail from "./child/detail";
import {
  setMommentLove,
  setMommentComment,
  getMommentComment,
} from "@/service/discover";

const { TextArea } = Input;
export default memo(function DetailComment(props) {
  const { userDetail, aid, uid, comment_num, refresh } = props;
  const [commentValue, setcommentValue] = useState("");
  const [commentList, setcommentList] = useState([]);
  const [currentAid, setcurrentAid] = useState(0);
  const [commentBox, setcommentBox] = useState({});
  const totalPage = Math.ceil(comment_num / MOMENT_DETAIL_COMMENT_PAGESIZE);
  const [page, setpage] = useState(1);
  const history = useHistory();

  const commentInput = (e) => {
    setcommentValue(e.target.value);
  };
  const getComment = async (isInit, num) => {
    let currentPage;
    if (isInit) {
      currentPage = num;
    } else {
      currentPage = page;
    }
  
    let obj = {
      page: currentPage,
      size: MOMENT_DETAIL_COMMENT_PAGESIZE,
      article_id: aid,
    };
    const { data } = await getMommentComment(obj);
    const ha = handleComment(data, 1);
    let lastComments = { ...commentBox };

    if (data.length > 0) {
      if (!commentBox[aid]) {
        commentBox[aid] = { list: [] };
      }
      const arr = deDuplication([...data, ...commentBox[aid].list]);
      const newArr = handleComment(arr, 1);
      newArr.reverse();
      setcommentList(newArr);


      if (!lastComments[aid]) {
        lastComments[aid] = { list: [] };
      }
      lastComments[aid].list = deDuplication([
        ...data,
        ...lastComments[aid].list,
      ]);
      setcommentBox(lastComments);

      if (ha.length == 0) {
        setpage(page + 1);
      }
    }
  };
  const submitComment = async (aid) => {
    let token = await isToken();
    if (!token) {
      history.push("/login");
      return;
    }

    let obj = {
      article_id: aid,
      user_id: userDetail.id,
      comment_id: "0",
      content: commentValue,
      avatar: userDetail.avatarUrl,
      user_name: userDetail.nick,
    };

    const res = await setMommentComment(obj);
    if (res.data) {
      message.success("评论成功!");
      setcommentValue("");
      getComment(true, 1);
    }

  };
  useEffect(() => {
    getComment();
  }, []);

  const setCurrentTextFocusAid = (id) => {
    setcurrentAid(id);
  };
  let timer = null;
  const loadMore = () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      setpage(page + 1);
    }, 600);
  };
  useEffect(() => {
    if (page > totalPage) return;
    getComment();
  }, [page]);

  return (
    <AskChildMomentDetailCommentWrapper>
      <div className="form">
        <TextArea
          bordered={false}
          className="text-area"
          allowClear={true}
          value={commentValue}
          rows={3}
          onChange={(e) => commentInput(e)}
          placeholder="留下友善的评论吧!"
        />
      </div>

      <div className="submit-box">
        <Button
          onClick={() => submitComment(aid)}
          type="primary"
          className="submit-btn"
        >
          提交回复
        </Button>
      </div>

      <div className="comments">
        <h2>当前页{page}</h2>
        <h2>{comment_num}</h2>
        <CommentDetail
          getComment={getComment}
          page={page}
          refresh={refresh}
          aid={aid}
          uid={uid}
          setCurrentTextFocusAid={setCurrentTextFocusAid}
          userDetail={userDetail}
          history={history}
          commentList={commentList}
        ></CommentDetail>
      </div>

      <div className="load-more">
        {commentBox[aid] && commentBox[aid].list.length < comment_num ? (
          <Button className="more-btn" onClick={() => loadMore()} size="small">
            点击加载更多评论...
          </Button>
        ) : (
          <Empty
            description="暂无更多评论数据!"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}
      </div>
    </AskChildMomentDetailCommentWrapper>
  );
});
